<template>
  <a-modal
    :visible="isFollowVisible"
    unmount-on-close
    :mask-closable="false"
    :closable="false"
    title-align="start"
    @ok="handleFollowConfirm"
    @cancel="handleFollowCancel"
  >
    <template #title>
      <CustomTitle title="客户跟进" />
    </template>
    <div v-spin-loading="{ spinning: isLoading, tip: '提交中...' }">
      <a-form :model="followForm" auto-label-width ref="followUpFormRef">
        <a-form-item label="跟进类型" field="trackType" :rules="[{ required: true, message: '请选择跟进类型' }]">
          <a-select v-model="followForm.trackType" placeholder="请选择">
            <a-option
              v-for="item in followUpTypes"
              :key="item.dictCode"
              :label="item.dictLabel"
              :value="item.dictCode"
            ></a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="跟进时间" field="trackDatetime" :rules="[{ required: true, message: '跟进时间不能为空' }]">
          <a-input placeholder="自动获取" disabled v-model="followForm.trackDatetime" />
        </a-form-item>
        <a-form-item label="跟进内容" field="contentDesc" :rules="[{ required: true, message: '请输入跟进内容' }]">
          <a-textarea placeholder="请输入" v-model="followForm.contentDesc" :max-length="200" allow-clear show-word-limit />
        </a-form-item>
        <a-form-item label="上传图片">
          <div>
            <a-upload
              list-type="picture-card"
              :file-list="upImagesList"
              multiple
              :show-preview-button="false"
              :custom-request="customUpload"
              :on-before-upload="beforeUpload"
              :on-before-remove="handelRemove"
              @exceed-limit="exceedLimit"
              :limit="8"
            />
            <div class="tip">注：最多可上传8张，单张不超过10M，支持JPG/JPEG/PNG格式</div>
          </div>
        </a-form-item>
        <a-form-item label="下次跟进设置" field="isNextSetting">
          <a-switch v-model="followForm.isNextSetting" @change="changeNextSetting" />
        </a-form-item>
        <template v-if="followForm.isNextSetting">
          <a-form-item label="下次跟进时间" field="nextDateTine" :rules="[{ required: true, message: '请选择下次跟进时间' }]">
            <a-date-picker
              :shortcuts="[]"
              @change="changeNextDateTine"
              v-model="followForm.nextDateTine"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              :disabled-date="disabledDate"
              :disabled-time="disabledTime"
            />
          </a-form-item>
          <a-form-item label="提醒时间">
            <a-date-picker
              v-model="followForm.nextTime"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              :disabled-date="disabledDate"
              :disabled-time="disabledTime"
            />
          </a-form-item>
          <a-form-item label="提醒内容">
            <a-textarea placeholder="请输入" v-model="followForm.nextContent" :max-length="200" show-word-limit />
          </a-form-item>
          <a-form-item label="跟进任务" :rules="[{ required: true, message: '请选择跟进任务' }]">
            <a-select placeholder="请选择跟进任务" v-model="followForm.stageTaskId" :filter-option="false" disabled>
              <a-option v-for="item in followTaskList" :value="item.value" :key="item.value">{{ item.name }}</a-option>
            </a-select>
          </a-form-item>
        </template>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance } from "vue";
import { Message } from "@arco-design/web-vue";
import type { RequestOption, FileItem } from "@arco-design/web-vue";
import dayjs from "dayjs";
import { debounce } from "lodash";
import { dictDataList, addTrack } from "@/apis/home";
import type { followTaskItem } from "@/apis";
import type { AddTaskParams } from "@/apis/home/type";
import type { FollowUpTypeDict, FileListItem } from "./types";
import { generateId, disabledTime, disabledDate } from "@/utils";
import { createNewFilename } from "@/utils/upload";
import useMultipartOssStore from "@/stores/modules/multipartOssStore";
import { followFormInit } from "./config";

const props = defineProps({
  modelValue: Boolean,
  currentInfoParam: {
    type: Object,
    default: () => ({
      stageTaskId: "",
      customerId: "",
      currentTaskTitle: "",
      currentCommonId: "",
      currentType: ""
    })
  }
});
const emit = defineEmits(["update:modelValue", "submitAfter", "cancel"]);
const { proxy } = getCurrentInstance() as any;
const ossStore = useMultipartOssStore();

const isFollowVisible = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});
const getNowDate = () => dayjs().format("YYYY-MM-DD HH:mm:ss");
const nowData = getNowDate();
const followForm = ref<AddTaskParams>({
  ...followFormInit,
  trackDatetime: nowData,
  nextDateTine: nowData,
  nextTime: nowData
});
// 跟进任务列表
const followTaskList = ref<followTaskItem[]>([]);

/**
 * 跟进图片
 * TODO:上传封装统一util
 */
const upImagesList = ref<FileListItem[]>([]);
const imageSize = 10;
const fileTypes = [".jpg", ".png", ".jpeg"];
const beforeUpload = (file: File) => {
  const suffix = file.name?.slice(file.name.lastIndexOf(".")) || "";
  const maxSize = file.size / 1024 / 1024 < imageSize;
  const isInFileType = fileTypes.includes(suffix);
  if (!isInFileType) {
    Message.error("请上传JPG/JPEG/PNG格式!");
    return false;
  }
  if (!maxSize) {
    Message.error(`单个视频大小不能超过${imageSize}M!`);
    return false;
  }
  return true;
};
const customUpload = async (option: RequestOption) => {
  try {
    const { uid: fileId = generateId(), file } = option.fileItem;
    const { file: fileData, objectName } = await createNewFilename(file);
    await ossStore.submit(objectName, fileData, fileId);
    await ossStore.setACL(objectName, "public-read");
    const fileUrl = await ossStore.signatureUrl(objectName);
    const url = fileUrl ? fileUrl.split("?")[0] : "";
    const fileObj: FileListItem = {
      fileName: fileData.name,
      fileUrl: url,
      url,
      fileId,
      uid: fileId
    };
    upImagesList.value.push({ ...fileObj });
  } catch (err) {
    console.log(err);
    alert(`文件上传错误：${JSON.stringify(err)}`);
  }
};
const exceedLimit = () => {
  Message.warning("最多可上传8张");
};
const handelRemove = (fileItem: FileItem) => {
  upImagesList.value = upImagesList.value.filter((item: FileListItem) => {
    return item.uid !== fileItem.uid;
  });
};

/**
 * 跟进类型（字典）
 */
const followUpTypes = ref<FollowUpTypeDict[]>([]);
const getFollowUpType = async () => {
  try {
    const { data = [] } = await dictDataList({ dictType: "FOLLER_UP_TYPE" });
    followUpTypes.value = data;
  } catch (err) {
    console.log(err);
  }
};

/**
 * 设置下次跟进时间，初始化数据
 * @param data
 */
const changeNextSetting = (data: boolean) => {
  if (data) {
    followForm.value.nextDateTine = dayjs().format("YYYY-MM-DD HH:mm:ss");
    followForm.value.nextTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
  }
};
const changeNextDateTine = e => {
  followForm.value.nextTime = e;
};

/**
 * 确认提交
 */
const isLoading = ref(false);
const getSubmitData = () => {
  const { stageTaskId, customerId } = props.currentInfoParam;
  followForm.value.customerId = customerId;
  followForm.value.crmFileCreateVOList = upImagesList.value?.map((item: FileListItem) => ({ url: item.url }));
  followForm.value.nextDateTine = dayjs(followForm.value.nextDateTine).format("YYYY-MM-DD HH:mm:ss");
  followForm.value.isNextSetting = followForm.value.isNextSetting ? 1 : 0;
  followForm.value.stageTaskId = followForm.value.isNextSetting ? stageTaskId : "";
};
const submitFollowFn = async () => {
  await nextTick();
  const valid = await proxy.$refs.followUpFormRef?.validate();
  if (valid) return Message.error("请完善必填项");
  try {
    isLoading.value = true;
    getSubmitData();
    //1流程任务  2跟进任务
    const currentType = props.currentInfoParam.currentType;
    currentType == 2 && (followForm.value.commTaskId = props.currentInfoParam.currentCommonId);
    await addTrack(followForm.value);
    isLoading.value = false;
    // 流程任务
    emit("submitAfter");
    handleFollowCancel();
  } catch (err) {
    isLoading.value = false;
    console.log(err);
  }
};
const handleFollowConfirm = debounce(submitFollowFn, 500);
/**
 * 取消
 */
const handleFollowCancel = () => {
  followForm.value = {
    ...followFormInit
  };
  emit("cancel");
};

/**
 * 初始化组件数据
 */
const initFollowData = () => {
  // 跟进任务
  followForm.value.stageTaskId = props.currentInfoParam.stageTaskId;
  followTaskList.value = [{ name: props.currentInfoParam.currentTaskTitle, value: props.currentInfoParam.stageTaskId }];
  getFollowUpType();
};

initFollowData();
</script>

<style scoped lang="scss"></style>
